package com.ttdevs.util;

import java.util.Calendar;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;

import com.meizu.mstore.license.ILicensingService;
import com.meizu.mstore.license.LicenseCheckHelper;
import com.meizu.mstore.license.LicenseResult;

public class CheckLicense {

	public static final int TRYTIMEOUT = 0; 
	public static final int CHECKFAIL = -1; 

	private final static int EXPIREDAYS = 2;
	private final static String APKPublicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCjl9U7eNgbdtZRfAmjyVAP/pfcK3dNK0Sc6xqwdeIuOAjzxq1AbjXfGXCMlEgHm9+rI5sd63fvuGFD4gNh3gqO8OqxBLO0X7x65nzwKsrz6jyiI9U3Gb4xBHhax7UihCQcgr7gmXhebTF9Dc9D0amwzKu3/+Q6MUui/Z/dpoeaEwIDAQAB";

	private Context context;
	private Handler handler;

	public CheckLicense(Context context, Handler handler) {
		this.context = context;
		this.handler = handler;
		check();
	}

	public void check() {
		Intent intent = new Intent(ILicensingService.class.getName());
		context.bindService(intent, connection, Context.BIND_AUTO_CREATE);
	}

	public void destory() {
		context.unbindService(connection);
	}

	private ServiceConnection connection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			System.out.println("LicensingService Disconnected");
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			ILicensingService mLicensingService = ILicensingService.Stub.asInterface(service);
			if (mLicensingService != null) {
				startCheck(mLicensingService);
			} else {
				handler.sendEmptyMessage(CHECKFAIL);
			}

		}
	};

	private void startCheck(ILicensingService mLicensingService) {
		LicenseResult result = null;
		try {
			result = mLicensingService.checkLicense(context.getPackageName());
		} catch (RemoteException e) {
			e.printStackTrace();
			handler.sendEmptyMessage(CHECKFAIL);
		}
		if (result.getResponseCode() == LicenseResult.RESPONSE_CODE_SUCCESS) {
			boolean bSuccess = LicenseCheckHelper.checkResult(APKPublicKey, result);
			if (bSuccess && result.getPurchaseType() == LicenseResult.PURCHASE_TYPE_NORMAL) {
				System.out.println(" ��ϲ �� ��֤�ɹ�������Ϊ��ʽ�汾 ");
			} else {
				Calendar beginCal = result.getStartDate();
				Calendar nowCal = Calendar.getInstance();
				long dif = nowCal.getTimeInMillis() - beginCal.getTimeInMillis();
				int passDay = (int) (dif / (24 * 60 * 60 * 1000));
				int left = EXPIREDAYS - passDay;

				if (left > 0) {
					System.out.println("������δ��");
					handler.sendEmptyMessage(left);
				} else {
					System.out.println("�������ѹ�");
					handler.sendEmptyMessage(TRYTIMEOUT);
				}
			}
		} else {
			handler.sendEmptyMessage(CHECKFAIL);
		}
	}
}
